﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Xml.Linq;
using System.Linq;
using System.Xml;
using System.Xml.XPath;
using Vk.Utils;

namespace Vk
{
    public class XMLResponse : ApiResponse
    {
        public XMLResponse(string xml)
        {
            Document = XDocument.Load(new StringReader(xml));
        }

        public override IApiNode GetNode(string path)
        {
            var node = Document.XPathSelectElement(path);
            if (node == null)
            {
                throw new Exception("Element with specified path wasn't found");
            }

            return new ApiXmlNode(node);
        }

        public override List<IApiNode> GetNodes(string path)
        {
            var nodes = Document.XPathSelectElements(path);
            if (nodes == null || !nodes.Any())
            {
                throw new Exception("Elements with specified path weren't found");
            }

            return nodes.Where(x => x != null).Select(x => (IApiNode)new ApiXmlNode(x)).ToList();
        }

        public new XDocument Document { get; }
        public override ApiResponseType Type
        {
            get { return ApiResponseType.XML; }
        }
    }
}